import base64
import uvicorn

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

import ddddocr
import requests
app = FastAPI()


class CaptchaBase64Request(BaseModel):
    uuid: str
    image_base64: str

class CaptchaImageUrlRequest(BaseModel):
    uuid: str
    image_url: str


@app.post('/recognize_captcha_base64')
def recognize_captcha_base64(request: CaptchaBase64Request):
    try:
        uuid = request.uuid
        image_base64 = request.image_base64

        if not uuid or not image_base64:
            return {'error': 'Missing required parameters'}, 400

        code = captcha_base64(image_base64)
        print(f"识别出的文字为: {code}")

        return {'code': 200,'data':code, 'uuid': uuid}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post('/recognize_captcha_image_url')
def recognize_captcha_image_url(request: CaptchaImageUrlRequest):
    try:
        uuid = request.uuid
        image_url = request.image_url

        if not uuid or not image_url:
            return {'error': 'Missing required parameters'}, 400

        code = captcha_url(image_url)
        print(f"识别出的文字为: {code}")

        return {'code': 200,'data':code, 'uuid': uuid}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))



def captcha_base64(image_base64):
    """
    使用ddddocr识别给定base64编码的图片验证码。

    :param image_base64: 验证码图片的base64编码字符串
    :return: 识别出的文字
    """
    # 创建ddddocr的实例
    ocr = ddddocr.DdddOcr()

    try:
        # 去掉base64字符串的前缀
        if image_base64.startswith("data:image/png;base64,"):
            image_base64 = image_base64.split(",")[1]

        # 解码base64字符串为图片数据
        img_bytes = base64.b64decode(image_base64)

        # 调试信息：打印解码后的图片数据长度
        print(f"解码后的图片数据长度: {len(img_bytes)} bytes")

        # 进行验证码识别
        captcha_text = ocr.classification(img_bytes)
        return captcha_text
    except Exception as e:
        # 捕获异常并打印错误信息
        print(f"识别验证码时发生错误: {e}")
        raise


def captcha_url(image_url):
    """
    从给定的URL下载验证码图片，并使用ddddocr识别验证码。

    :param image_url: 验证码图片的URL
    :return: 识别出的文字
    """
    # 创建ddddocr的实例
    ocr = ddddocr.DdddOcr()

    # 下载图片数据
    response = requests.get(image_url)
    if response.status_code != 200:
        raise Exception(f"无法下载图片, 状态码: {response.status_code}")
    with open("coptcha/coptcha_01.png", "wb") as f:
        f.write(response.content)
    img_bytes = response.content

    # 进行验证码识别
    captcha_text = ocr.classification(img_bytes)

    return captcha_text



if __name__ == '__main__':
    uvicorn.run(app, host="0.0.0.0", port=5000)